package com.caiyi.financial.nirvana.sms.filters;

import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsUserAuditTypeEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.param.SendMsgParam;
import com.youyu.common.utils.YyAssert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

public class ContentFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void run(FilterChain filterChain) {
        SendMsgParam param = filterChain.getParam();
        String content = param.getContent();
        SmsUser user = filterChain.getSmsUser();
        String key = String.format(JedisKey.SMS_SIGN, user.getAccount());
        Set<String> signList = JedisService.zrevrange(key, 0, -1);
        YyAssert.isFalse(signList == null || signList.isEmpty(), ReturnCodeEnum.CONTENT_SIGN_ERROR);
        String contentSign = null;
        int index = content.lastIndexOf("【");
        boolean with = content.endsWith("】");
        if (with && index != -1) {
            contentSign = content.substring(index);
        }
        with = content.startsWith("【");
        index = content.indexOf("】");
        if (with && index != -1) {
            contentSign = content.substring(0, index + 1);
        }
        //如果不包含签名
        if (contentSign == null) {
            content = signList.iterator().next() + content;
            param.setContent(content);
        } else {
            if (user.getAuditType() == SmsUserAuditTypeEnum.TEMPLATE.index) {
                YyAssert.isFalse(!signList.contains(contentSign), ReturnCodeEnum.CONTENT_SIGN_ERROR);
            }
        }
        filterChain.doFilter();
    }
}
